﻿using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.ServiceModel;
using System.Web.Routing;
using System.ServiceModel.Activation;
using System.Net;
using WCFServiceWebRole1.DataObjects;
using GlobalObjects;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.IO;

namespace IotWebService_Intergration_Test
{
    [TestClass]
    public class DeviceIIS
    {

        [ClassInitialize]
        public static void ClassInitialize(TestContext context)
        {
       //     RouteTable.Routes.Add(new ServiceRoute("device", 
       //                   new ServiceHostFactory(), typeof(WCFServiceWebRole1.Services.device)));
        }

        //testing deviceregister Method - Path 4
        [TestMethod]
        [ExpectedException(typeof(WebException), "Raise exception when service returns exception")]
        public void deviceregister_IIS_valid()
        {
            DeviceRegistrationRequestDataContract registration = new DeviceRegistrationRequestDataContract()
            {
                DeviceId = 1060,
                Sensors = new List<SensorRegistrationRequest>()
                {
                    new SensorRegistrationRequest(){
                        Fault_tolerance=60,Interval_measure="5",Interval_send="20",Make="GHI",Metadata="NotYetTested",
                        Name="RegisterSensor",Type="Weather"
                    }
                }
            };
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:7198/Services/device.svc/device");
            httpWebRequest.ContentType = "text/json;";
            httpWebRequest.Headers.Add("Authorization: APIKey " + "bf9e6201-63a6-4422-a2f4-40e27ce468d4");
            //testDevice.APIKey);
            httpWebRequest.Method = "POST";

            JavaScriptSerializer js2 = new JavaScriptSerializer();
            string json = js2.Serialize(registration);


            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(json);

                streamWriter.Flush();
                streamWriter.Close();
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                Assert.AreEqual("\"Success\"", result.ToString());
                // Debug.WriteLine(result);
            }
        }
    }
}
